var clientUrl = "http://10.138.42.215:19800/common/inter";//接口地址 定量
var clientUrl2 = "http://10.138.42.215:19801/common/inter";//接口地址 定量
var param = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_003", "fresh": "1"};//接口请求参数 变量   新增用户数
var params2 = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_002", "fresh": "1"}//累计用户数
var params = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_004", "fresh": "1"}//活跃用户活跃率
var params3 = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_006", "fresh": "1"}//商品运营-订单用户数+订单用户转换率+订单额
var params4 = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_007", "fresh": "1"}//商品运营-订单用户数+订单用户转换率+订单额
var params5 = {"dateDtKpi": getNowFormatDate().toString(), "dataType": "dp1169_app_anlyze_008", "fresh": "1"}//商品运营-订单用户数+订单用户转换率+订单额
var params6 = {"dateDtKpi": getNowFormatDate().toString(),"dataType": "dp1169_app_anlyze_001", "fresh": "1"}//平台运营
var chartsArray = [];

$(function () {
	 //显示当前时间
            var now = new Date();
            //格式化日，如果小于9，前面补0
            var day = ("0" + now.getDate()).slice(-2);
            //格式化月，如果小于9，前面补0
            var month = ("0" + (now.getMonth() + 1)).slice(-2);
            //拼装完整日期格式
            var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
            //完成赋值
            $('#date').val(today);
	$("#date").change(function(){
		if(new Date($("#date").val())>new Date()){
			param.dateDtKpi='20180905';
		}else{
			param.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params2.dateDtKpi='20180905';
		}else{
			params2.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params3.dateDtKpi='20180905';
		}else{
			params3.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params4.dateDtKpi='20180905';
		}else{
			params4.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params5.dateDtKpi='20180905';
		}else{
			params5.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params.dateDtKpi='20180905';
			
		}else{
			params.dateDtKpi=$("#date").val();
		}
		if(new Date($("#date").val())>new Date()){
			params6.dateDtKpi='20180905';
			
		}else{
			params6.dateDtKpi=$("#date").val();
		}
		loadCharts();
	})
    // requestDataByAjax(clientUrl,param,getAjaxData);
   loadCharts()
});

function loadCharts(){
	 requestDataByAjax(clientUrl, param, drawLineEcharts);
    requestTopdata();
    requestOrderdata();
    orderuser();
    draw();
    requestOrderuser();
    //平台运营
    getPlatYunyingData();
    $(window).resize(resetCharts);
	
}
//请求完数据之后的回调函数  用于书写echart的独立逻辑
function getAjaxData(model) {
    console.log(model);
    console.log(model.legend);
    console.log(model.xAxis);
    console.log(model.series);

}

//请求数据接口
function requestDataByAjax(clientUrl, param, callback) {
    $.ajax({
        url: clientUrl,
        data: param,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            console.log(data)
            var model = new dataModel(data);

            callback(model);
        }
    });
};

//累计用户数
function requestTopdata() {
    $.ajax({
        url: clientUrl,
        data: params2,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            console.log(data)
            $("#text tbody").html("");
            var tr = [];
            var up = '';
            var down = '';
            $.each(data.monthly_trend, function (index, item) {
                var mTr = '';
                mTr += '<tr><td>' + item.appname + '</td><td>' + item.user_resource_appdown + '<i class="iconfont ' + judgeImage(item.user_resource_appdown_flag) + ' "></i>'
                    + '</td><td>' + item.user_resource_increment + '<i class="iconfont ' + judgeImage(item.user_resource_increment_flag) + '"></i>'
                    + '</td><td>' + item.user_resource_active_user_num + '<i class="iconfont ' + judgeImage(item.user_resource_active_user_num_flag) + '"></i>'
                    + '</td><td>' + parseFloat((item.user_resource_monthly_activity)*100).toFixed(2) + '%<i class="iconfont ' + judgeImage(item.user_resource_monthly_activity_flag) + '"></i></td></tr>';
                tr.push(mTr);

            });
            $("#text tbody").html(tr.join(''));

        }

    });
}
//商品运营-订单用户数+订单用户转换率+订单额
function requestOrderdata() {
    $.ajax({
        url: clientUrl,
        data: params3,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            console.log(data)
            $("#text2 tbody").html("");
            var tr = [];
            var up = '';
            var down = '';
            $.each(data.monthly_trend, function (index, item) {
                var mTr = '';
                mTr += '<tr><td>' + item.appname + '</td><td>' + item.ecology_order_mon_num + '<i class="iconfont ' + judgeImage(item.ecology_order_mon_num_flag) + ' "></i>'
                    + '</td><td>' + item.ecology_order_mon_price + '<i class="iconfont ' + judgeImage(item.ecology_order_mon_price_flag) + '"></i>'
                    + '</td><td>' + parseFloat(item.ecology_order_avge_price*10000).toFixed(2) + '<i class="iconfont ' + judgeImage(item.ecology_order_avge_price_flag) + '"></i></td></tr>';
                tr.push(mTr);
            });
            $("#text2 tbody").html(tr.join(''));

        }

    });
}
function judgeImage(value) {
    var num = parseInt(value);
    if (num == 0) {
        return "icon-jiantou";
    } else if (num > 0) {
        return " icon-increase ";
    } else if (num < 0) {
        return " icon-slide ";
    }
}


//生成图例
function joinLegeng(data) {
    var legend = [];
    $.each(data.monthly_trend, function (index, item) {
        if (legend.indexOf(item.appname) == -1) {
            legend.push(item.appname);
        }
    });
    return legend;
}
//生成xAxis
function joinxAxis(data) {
    var xAxis = [];
    $.each(data.monthly_trend, function (index, item) {
        if (xAxis.indexOf(item.mon) == -1) {
            xAxis.push(item.mon);
        }
    });
    return xAxis;
}
//生成series
function joinSeries(data, legend, xAxis) {
    var series = [];
    $.each(legend, function (index, item) {
        var mSerise = {"name": item};
        var mData = Array.apply(null, Array(xAxis.length)).map(() => 0);
        var mDatas = Array.apply(null, Array(xAxis.length)).map(() => 0);
        $.each(data.monthly_trend, function (ind, it) {
            if (it.appname == item) {
                var num = xAxis.indexOf(it.mon);
                if (num != -1) {
                    mData[num] = parseFloat(it.new_cnt);
                    mDatas[num] = parseFloat(it.rate * 100).toFixed(2);
                }
                ;
            }
            ;
        });
        mSerise.data = mData;
        mSerise.datas = mDatas;
        series.push(mSerise);
    });

    return series;
}


//封装数据的实体
function dataModel(data) {
    var legend = joinLegeng(data);
    var xAxis = joinxAxis(data);
    this.legend = legend;
    this.xAxis = xAxis;
    this.series = joinSeries(data, legend, xAxis);
};
//封装数据的实体
function orderdataModel(data) {
    var legend = joinLegeng(data);
    var xAxis = joinxAxis(data);
    this.legend = legend;
    this.xAxis = xAxis;
    this.series = orderjoinSeries(data, legend, xAxis);
};
//记录echart对象
function recordCharts(charts) {
    if (chartsArray.indexOf(charts) == -1) {
    }
};
//重置图表
function resetCharts() {
    $.each(chartsArray, function (index, item) {
        console.log(item);
        $(item).resize();
    })
    chartsArray.push(charts);
}

//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
    //var date = new Date(new Date().getTime() - 86400000);
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

// 新增用户数趋势
function drawLineEcharts(model) {
    var series = [];
    $.each(model.series, function (index, item) {
        series.push({
            name: item.name,
            type: 'line',
            symbol: 'circle',
            smooth: true,
            lineStyle: lineStyle,
            stack: '总量',
            data: item.data
        });
    })
    let ec001_line = echarts.init($("#ec001_line")[0]);
    ec001_line.clear();
    ec001_line.setOption(opt_line);
    recordCharts(ec001_line);
    ec001_line.setOption({
        grid: {
            top: '29%',
            bottom: '20%',
            left: '15%',
            right: '5%',
        },
        title: {
            text: ''
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: model.legend
        },
        /*toolbox: {
         feature: {
         magicType: {type: ['line', 'bar']},
         },
         iconStyle:{
         color:'#0cf'
         }
         },*/
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: model.xAxis
        },
        yAxis: {
            type: 'value',
            name:'人数'
        },
        series: series
    });
}

// 活跃用户数和活跃率趋势图
function draw() {
    $.ajax({
        url: clientUrl,
        data: params,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            var model = new dataModel(data);
            console.log(model)
            var series1 = [];
            var vlaues = [];
            $.each(model.series, function (index, item) {

                series1.push({
                    name: item.name,
                    type: 'line',
                    symbol: 'circle',
                    smooth: true,
                    lineStyle: lineStyle,
                    yAxisIndex: 0,
                    data: item.data
                });


            });
            $.each(model.series, function (index, item) {
                series1.push({
                    name: item.name,
                    type: 'bar',
                    itemStyle: {color: colors[index]},
                    barWidth: '20%',
                    yAxisIndex: 1,
                    //data: parseFloat(item.datas).toFixed(2)
                    data:item.datas
                });
            });
            // 活跃用户数和活跃率趋势图
            let ec002_lineBar = echarts.init($("#ec002_lineBar")[0]);
            ec002_lineBar.clear();
            ec002_lineBar.setOption(opt_line);
            recordCharts(ec002_lineBar);
            ec002_lineBar.setOption(opt_bar_vertical);
            ec002_lineBar.setOption({
                grid: {
                    top: '29%',
                    bottom: '25%',
                    left: '15%',
                    right: '10%',
                },
                tooltip: {
                    position: 'top',
                    formatter: function (params) {
                        console.log(params);
                        var arr=[];
                        $.each(params,function(index,item){
                            if(index>params.length/2-1){
                                arr.push(params[index].seriesName+":"+params[index].data+"%</br>");
                            }else{
                                arr.push(params[index].seriesName+":"+params[index].data+"</br>");
                            }

                        });
                        return arr.join('');

                    }
                },

                xAxis: {
                    // name: '月份',
                    data: model.xAxis,

                },
                yAxis: [
                    {
                        name: '人数',
                        //minInterval: 200,
                        splitLine: {
                            show: false
                        },
                        splitNumber:3

                    },
                    {
                        name: '活跃率',
                        //minInterval: 20,
                        axisLine: axisLine_Y,

                        axisTick: {
                            show: false,
                        },

                        axisLabel: {
                            formatter: '{value} %'
                        },
                        splitLine: splitLine,
                        splitNumber:3
                    },

                ],
                series: series1
            });


        }

    });
}

function orderuser() {
    $.ajax({
        url: clientUrl,
        data: params4,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            var model = new dataModel(data);
            console.log(model)
            var series1 = [];
            $.each(model.series, function (index, item) {

                series1.push({
                    name: item.name,
                    type: 'line',
                    symbol: 'circle',
                    smooth: true,
                    lineStyle: lineStyle,
                    yAxisIndex: 0,
                    data: item.data
                });


            });
            let ec004_line = echarts.init($("#ec004_line")[0]);
            ec004_line.clear();
            ec004_line.setOption(opt_line);
            recordCharts(ec004_line);
            ec004_line.setOption({
                grid: {
                    top: '20%',
                    bottom: '20%',
                    left: '15%',
                    right: '5%',
                },
                xAxis: {
                    data: model.xAxis
                },
                yAxis: {
                    name: '订单数',
                    minInterval: 50,
                },
                series: series1
            });
        }
    });

}

function requestOrderuser(){
    $.ajax({
        url: clientUrl,
        data:params5,
        type: 'get',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //错误处理k
        },
        success: function (data) {
            var model=new orderdataModel(data)
            console.log(model)
            var series1=[];
            var xData=["独立", "有操作",  "购物车", "下单", "付款"];
            var num=[]
            $.each(model.legend,function(index,item){
                $.each(xData,function(ind,it){
                    num.push(model.series[index].data[ind]);
                });
            });

            var min=Math.min.apply(null,num);
            var max=Math.max.apply(null,num);

            let ec005_data = [];
            $.each(model.legend,function(index,item){
                $.each(xData,function(ind,it){
                    ec005_data.push([index,ind,parseInt(model.series[index].data[ind])]);
                    //console.info(model.series[index].data[ind]);
                });
            });

            let ec005_scatter = echarts.init($("#ec005_scatter")[0]);
            //ec005_scatter.setOption(opt_scatter);


            ec005_data= ec005_data.map(function (item) {
                return [item[1], item[0], item[2]];
            });

            option = {
                tooltip: {
                    position: 'top',
                    formatter: function (params) {
                        var x=model.series[params.value[1]].ysdata[params.value[0]];
                        console.log(params.value[1],params.value[0],x)
                        return  model.legend[params.value[1]]+'-' +xData[params.value[0]] +  ":"+x  ;
                        // return  model.legend[params.value[1]]+'-' +xData[params.value[0]] +  ":"+params.value[2]  ;
                    }
                },
                color: '#2caafc',
                textStyle: {
                    fontFamily: 'PingFang SC, microsoft yahei,微软雅黑, sans-serif',
                    color: cTextWeek,
                    fontSize: 10 * bodyScale
                    // width:'120%'
                },
                grid: {
                    bottom: "2%",//底边留空
                    top: '15%',
                    left: '3%',
                    right: '13%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: xData,
                    name:'用户数',
                    axisTick: { //小刻度线
                        show: false
                    },
                    axisLine: { //坐标轴
                        lineStyle: {
                            color: cTextWeek
                        }
                    },

                },
                yAxis: {
                    type: 'category',
                    data: model.legend,
                    axisTick: { //小刻度线
                        show: false
                    },
                    axisLine: { //坐标轴
                        lineStyle: {
                            color: cTextWeek
                        }
                    },
                },
                series: [{
                    name: '订单用户转化率',
                    type: 'scatter',
                    left: '15%',
                    top: '10%',
                    bottom:'10%',
                    symbolSize: function (val) {
                        return parseInt((val[2]-min)/(max-min)*50)* bodyScale
                    },
                    data: ec005_data,
                    animationDelay: function (idx) {
                        return idx * 5;
                    }
                }]
            };
            ec005_scatter.setOption(option);
        }
    })
}


function orderjoinSeries(data,legend,xAxis){
    var series=[];
    $.each(legend,function(index,item){
        var mSerise={"name":item};
        var mData=Array.apply(null, Array(xAxis.length)).map(() => 0);
        var ysdata=Array.apply(null, Array(xAxis.length)).map(() => 0);
        $.each(data.monthly_trend,function(ind,it){
            if(it.appname==item){
                var num=xAxis.indexOf(it.mon);
                if(num!=-1){
                    mData[0]=Math.log(it.all_user);
                    mData[1]=Math.log(it.no_operstion_user);
                    mData[2]=Math.log(it.shopping_user);
                    mData[3]=Math.log(it.order_user);
                    mData[4]=Math.log(it.payment_user);
                    for(var x=0;x<mData.length;x++){
                        if(mData[x]=="-Infinity"||mData[x]=="NaN"){
                            mData[x]=0;
                        }
                    };

                    ysdata[0]=it.all_user;
                    ysdata[1]=it.no_operstion_user;
                    ysdata[2]=it.shopping_user;
                    ysdata[3]=it.order_user;
                    ysdata[4]=it.payment_user;

                };
            };
        });
        mSerise.data=mData;
        mSerise.ysdata=ysdata;
        series.push(mSerise);
    });

    return series;
}


//平台运营数据
function getPlatYunyingData() {
    $.ajax({
        url: clientUrl2,
        data:params6,
        type: 'get',
        dataType: 'json',
        error: function () {
        },
        success: function (data) {
        	if(data.monthly_trend.length>0){
            console.log(data);
            $("#top1_1").text(data.monthly_trend[0].per_capita_visit_number);
            $("#top1_2").text(data.monthly_trend[0].per_capita_visit_length);
            $("#top1_3").text(data.monthly_trend[0].per_capita_access_page_number);
            // 人均访问次数
          let  ec006_hBar = echarts.init($("#ec006_hBar")[0]);
            ec006_hBar.clear();
            ec006_hBar.setOption(opt_bar_horizon);
            ec006_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'次数'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, data.monthly_trend[0].per_capita_visit_number, 0],
                    }

                ]
            });

            // 人均访问时长
            let ec007_hBar = echarts.init($("#ec007_hBar")[0]);
            ec007_hBar.clear();
            ec007_hBar.setOption(opt_bar_horizon);
            ec007_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'分钟'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, data.monthly_trend[0].per_capita_visit_length, 0],
                    }

                ]
            });
            // 人均访问页面数
            let ec008_hBar = echarts.init($("#ec008_hBar")[0]);
            ec008_hBar.clear();
            ec008_hBar.setOption(opt_bar_horizon);
            ec008_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'页面数'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, data.monthly_trend[0].per_capita_access_page_number, 0],
                    }

                ]
            });

           }else{
           	$("#top1_1").text(0);
            $("#top1_2").text(0);
            $("#top1_3").text(0);
           let  ec006_hBar = echarts.init($("#ec006_hBar")[0]);
            ec006_hBar.clear();
            ec006_hBar.setOption(opt_bar_horizon);
            ec006_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'次数'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, 0, 0],
                    }

                ]
            });

            // 人均访问时长
            let ec007_hBar = echarts.init($("#ec007_hBar")[0]);
            ec007_hBar.clear();
            ec007_hBar.setOption(opt_bar_horizon);
            ec007_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'分钟'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, 0, 0],
                    }

                ]
            });
            // 人均访问页面数
            let ec008_hBar = echarts.init($("#ec008_hBar")[0]);
            ec008_hBar.clear();
            ec008_hBar.setOption(opt_bar_horizon);
            ec008_hBar.setOption({
                grid: {
                    top: '10%',
                    bottom: '20%',
                    left: '15%',
                    right: '12%',
                },
                xAxis: {
                    name:'页面数'
                },
                yAxis: {
                    data: ['乐家', '乐农', '车小微']
                },
                series: [
                    {
                        type: 'bar',
                        value: 5,
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    return colors[params.dataIndex]
                                }
                            }
                        },
                        data: [0, 0, 0],
                    }

                ]
            });

           }
            // 人均访问次数
           



        }
    });
}